package com.imooc.controller;

import com.imooc.controller.viewobject.UserVO;
import com.imooc.error.BusinessException;
import com.imooc.error.EmBusinessError;
import com.imooc.response.CommonReturnType;
import com.imooc.service.UserService;
import com.imooc.service.model.UserModel;
import com.imooc.utils.CodeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    //用户获取otp短信接口
    @PostMapping("/getotp")
    public CommonReturnType getOtp(@RequestParam(name = "telephone") String telephone){
        //按规则生成OTP验证码
        String otpCode = CodeUtil.generateCode();

        //将OTP验证码同对应用户的手机号关联,使用httpSession绑定他的手机号与otpCode
        httpServletRequest.getSession().setAttribute(telephone,otpCode);


        //将OTP验证码通过短信通道发送给用户,省略
        System.out.println("telephone="+telephone+" &otpCode="+otpCode);

        return CommonReturnType.success();
    }

    @RequestMapping("/get")
    public CommonReturnType getUser(@RequestParam(name = "id") Integer id) throws BusinessException {
        UserModel userModel = userService.getUserById(id);

        //如果获取的用户信息不存在
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }

        UserVO userVO = covertFromModel(userModel);
        return CommonReturnType.success(userVO);
    }

    private UserVO covertFromModel(UserModel userModel) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel, userVO);

        return userVO;
    }


}
